import { gm } from '../../managers/GameManager';
import { Observable, of } from 'rxjs';
import { _decorator, Component, Node, director, System, Eventify, log, js, sys } from 'cc';
import { i18n } from '../../i18n';
import { DataConfig } from '../../managers/DataConfig';
import { DevConfig } from '../../managers/DevConfig';
const { ccclass, property } = _decorator;

const RecordTime = 240;

@ccclass('ByteDanceRecorderManager')
class ByteDanceRecorderManager extends Eventify(System) {

    public static instance: ByteDanceRecorderManager;
    static ID = 'bytedance_recorder_system';

    registerSystem() {
        director.unregisterSystem(director.getSystem(ByteDanceRecorderManager.ID));
        director.registerSystem(ByteDanceRecorderManager.ID, bdrm, System.Priority.MEDIUM);
        bdrm.init();
    }

    init() {
        log(`<${js.getClassName(this)}>`, 'init');

        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            this.ByteDanceRecorderInit();
        }
    }

    private callBackBegin: any = null;       //开始录屏回调
    private callBackEnd: any = null;         //结束录屏回调
    private callBackErr: any = null;         //录屏失败回调
    private recorder: any = null;            //录屏组件

    //开始录屏
    private recorderBegin() {
        if (this.callBackBegin != null) {
            this.callBackBegin.call(this);
        }
    }
    //结束录屏
    private recorderEnd(res) {
        if (this.callBackEnd != null) {
            this.callBackEnd.call(this, res);
        }
    }
    //录屏失败
    private recorderErr() {
        if (this.callBackErr != null) {
            this.callBackErr.call(this);
        }
    }

    res: any = null;

    time: number = 0;
    recording: boolean = false;
    isError: boolean = false;

    alreadyStop: boolean = false;

    update(t) {
        if (this.recording) {
            this.time += t;
            if (this.time > RecordTime) {
                this.stopRecoder(() => { });
                this.alreadyStop = true;
            }
        }
        // console.log('@alreadyStop', this.alreadyStop);
    }

    /**
     * 抖音录屏组件
     */
    public ByteDanceRecorderInit() {
        console.log("抖音录屏组件初始化");
        let self = this;

        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            this.recorder = globalThis.tt.getGameRecorderManager();

            //注册开始录屏事件
            this.recorder.onStart(function (res) {
                console.log("=========> 开始录屏：", res);
                self.recorderBegin();
            });
            //注册结束录屏事件
            this.recorder.onStop(function (res) {
                console.log("=========> 录屏结束：", res);
                this.alreadyStop = true;
                bdrm.res = res;
                self.recorderEnd(res);
            });
            //注册录屏错误事件
            this.recorder.onError(function (res) {
                console.log("=========> 录屏出错：", res);
                self.isError = true;
                self.recorderErr();
            });
        }
    }

    //开始录屏
    public startRecoder(callback) {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            let ts = RecordTime + 5;
            let frame = 24;

            if (sys.os == sys.OS.ANDROID) {
                ts = RecordTime + 5;
                frame = 24;
            } else if (sys.os == sys.OS.IOS) {
                ts = RecordTime + 5;
                frame = 15;
            }

            if (this.recorder != null) {
                this.callBackBegin = callback;

                this.alreadyStop = false;
                this.time = 0;
                this.recording = true;
                this.isError = false;

                this.recorder.start({
                    duration: ts,   //录屏时长300s
                    frameRate: frame,   //录屏帧率24
                });
            }
        } else {
            callback(true);
        }
    }

    //停止录屏
    public stopRecoder(callback) {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            if (this.alreadyStop) {
                callback(true);
            } else {
                if (this.recorder != null) {
                    this.callBackEnd = callback;
                    this.recorder.stop();
                    this.recording = false;
                    console.log('record time', this.time);
                }
            }
        } else {
            callback(true);
        }
    }

    public pauseRecorder() {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            if (!this.alreadyStop) {
                this.recorder.pause();
                this.recording = false;
            }
        }
    }

    public resumeRecorder() {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            if (!this.alreadyStop) {
                this.recorder.resume();
                this.recording = true;
            }
        }
    }

    sharing = false;
    public share() {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            if (this.sharing) {
                gm.frontTipShow(`${i18n.t('_.wait')}`, 1).subscribe();
            } else {
                return new Observable(observer => {
                    this.sharing = true;
                    globalThis.tt.shareAppMessage({
                        title: DevConfig.hard ? DataConfig.title : DataConfig.title2,
                        channel: "video",
                        extra: {
                            videoPath: bdrm.res.videoPath, //录屏后得到的文件地址
                            withVideoId: true,
                        },
                        success: (_r) => {
                            this.sharing = false;
                            globalThis.tt.showToast({
                                // title: "分享成功",
                                title: i18n.t('f.sharesuc'),
                            });
                            observer.next(true);
                            observer.complete();
                        },
                        fail: (e) => {
                            this.sharing = false;
                            globalThis.tt.showToast({
                                // title: "分享失败",
                                title: i18n.t('f.sharefail'),
                                icon: 'fail'
                            });
                            observer.next(false);
                            observer.complete();
                        },
                    });
                });
            }
        } else {
            gm.frontTipShow('分享成功', 1).subscribe();
            return of(true);
        }
    }
}

globalThis.ByteDanceRecorderManager = ByteDanceRecorderManager;

export const bdrm = ByteDanceRecorderManager.instance = new ByteDanceRecorderManager();